import {
  getToken,
  setToken,
  removeToken,
  setTimeStamp
} from '@/utils/auth'
import Cookies from 'js-cookie'
import {
  getUserInfo,
  loginApi
} from '@/api/user'
import { getEmployeesInfo } from '@/api/employees'

export default {
  namespaced: true,
  state: {
    Token: getToken(),
    userInfo: {}
  },
  mutations: {
    SET_TOKEN(state, newData) {
      state.Token = newData
      setToken(newData)
      // 设置时间戳
      setTimeStamp()
    },
    REMOVE_TOKEN(state) {
      state.Token = null
      removeToken()
    },
    SAVE_USERINFO(state,newData){
      state.userInfo = newData
    },
    REMOVE_USERINFO(state){
      state.userInfo = {}
    }
  },
  actions: {
    logout(context){
      context.commit('REMOVE_TOKEN')
      context.commit('REMOVE_USERINFO')
    },

    async login(context, newData) {
      try {
        let res = await loginApi(newData)
        if (res.success) {
          let token = res.data
          // console.log(res);
          context.commit('SET_TOKEN', token)
        }
      } catch (error) {
        console.log(error);
        return Promise.reject(error)
      }
    },

    async getUserInfo(context,newData){
      const res = await getUserInfo()
      // console.log(res.data);
      const baseRes = await getEmployeesInfo(res.data.userId)
      let result = {...res.data,...baseRes.data}
      // console.log(res);
      context.commit('SAVE_USERINFO',result)
      return result
    }
  }
}
